<template>
  <div class="data-map" v-loading="loading" :class="{'no-check':getReadOnlyFlag}">
    <!-- 标题 -->
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" class="demo-ruleForm">
      <!-- <div class="new-title">数据项映射属性</div> -->
      <div class="new-flew">
        <label for="input-block">转换名称:</label>
        <div class="input-block">
          <el-form-item prop="name" label-width="0">
            <el-input
              v-model="ruleForm.name"
              size="small"
              clearable
              placeholder="转换名称"
              @input="setName"
            ></el-input>
          </el-form-item>
        </div>
      </div>
      <div ref="tbBlock" class="table-block">
        <el-table
          ref="dataMap"
          :data="ruleForm.dataMapList"
          stripe
          border
          width="100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" :selectable="checkSelectable"></el-table-column>
          <el-table-column
            key="1"
            label="源标识符"
            prop="sourceColumnName"
            width="120"
            align="left"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            key="2"
            label="源名称"
            prop="sourceColumnChineseName"
            width="120"
            align="left"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            key="3"
            label="源类型"
            prop="sourceColumnType"
            width="120"
            align="left"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column width="220" align="left">
            <template slot="header">
              <span class="text-required">*</span>
              <span>目标标识符</span>
            </template>
            <template slot-scope="scope">
              <div
                v-if="!getReadOnlyFlag"
                style="display: flex; align-items: center; justify-content: center;"
                class="type_meta_data"
              >
                <el-form-item
                  :prop="`dataMapList.${scope.$index}.logicColumnName`"
                  :rules="tableRules.logicColumnName"
                  style="margin-left: 0px;"
                  label-width="0"
                >
                  <el-input
                    v-model="scope.row.logicColumnName"
                    size="small"
                    clearable
                    @input="vaildEnName"
                    :disabled="scope.row.isStandard==1"
                    style="margin-right:10px"
                  ></el-input>
                </el-form-item>
                <el-tooltip class="item" effect="light" content="添加" placement="top">
                  <i
                    :disabled="dis"
                    class="btn-style iconfont icon-wenbentianjia font_family"
                    @click="setMetaData(scope.$index,scope.row)"
                  ></i>
                </el-tooltip>
                <el-tooltip class="item" effect="light" content="清除" placement="top">
                  <i
                    v-show="scope.row.isStandard==1"
                    class="btn-style iconfont icon-shanchu font_family"
                    @click="clearNewColumnInfo(scope.$index,scope.row)"
                  ></i>
                </el-tooltip>
              </div>
              <span v-if="getReadOnlyFlag">{{ scope.row.logicColumnName }}</span>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip align="center">
            <template slot="header">
              <span class="text-required">*</span>
              <span>目标名称</span>
            </template>
            <template slot-scope="scope">
              <div
                v-if="!getReadOnlyFlag"
                style="display: flex; align-items: center; justify-content: center;"
                class="type_meta_data"
              >
                <el-form-item
                  :prop="`dataMapList.${scope.$index}.logicColumnChineseName`"
                  :rules="tableRules.logicColumnChineseName"
                  style="margin-left: 0px;"
                  label-width="0"
                >
                  <el-input
                    v-model="scope.row.logicColumnChineseName"
                    size="small"
                    @input="isUpdateForm = true"
                    :disabled="scope.row.isStandard==1"
                  ></el-input>
                </el-form-item>
              </div>
              <span v-if="getReadOnlyFlag">{{ scope.row.logicColumnChineseName }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center">
            <template slot="header">
              <span class="text-required">*</span>
              <span>目标类型</span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                v-if="!getReadOnlyFlag"
                :prop="`dataMapList.${scope.$index}.logicColumnType`"
                :rules="tableRules.logicColumnType"
                style="margin-left: 0px;"
                label-width="0"
              >
                <el-select
                  v-model="scope.row.logicColumnType"
                  size="small"
                  :disabled="scope.row.isStandard==1"
                  @change="isUpdateForm = true"
                >
                  <el-option
                    v-for="item in getDictionaryList.ColumnType"
                    :key="item.dataValue"
                    :label="item.dataName+'('+item.dataValue+')'"
                    :value="item.dataValue"
                  ></el-option>
                </el-select>
              </el-form-item>
              <span v-if="getReadOnlyFlag">{{ scope.row.logicColumnType }}</span>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" label="添加规则" align="center" width="240">
            <template slot-scope="scope">
              <el-form-item
                v-if="!getReadOnlyFlag"
                :prop="`dataMapList.${scope.$index}.rule`"
                :rules="tableRules.rule"
              >
                <el-input v-model="scope.row.rule" class="new-input" disabled></el-input>
                <el-tooltip class="item" effect="light" content="修改" placement="top">
                  <i
                    class="btn-style iconfont icon-xiugaibianji font_family"
                    @click.stop="edit(scope.$index, scope.row)"
                  ></i>
                </el-tooltip>
              </el-form-item>
              <span v-if="getReadOnlyFlag">{{ scope.row.rule }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
    <metaData ref="metaData" @setMeta="getMetaData"></metaData>
    <!-- 规则弹框 -->
    <el-dialog
      title="添加规则"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
      append-to-body
      :close-on-click-modal="false"
    >
      <span>
        <!-- 内容区域 -->
        <div class="new-flex">
          <!-- 树结构 -->
          <div class="content-child">
            <div class="line-flex">
              <div style="width:90px">函数搜索：</div>
              <el-input v-model="filterTextNo" clearable placeholder="输入关键字进行过滤">
                <i slot="suffix" class="el-input__icon el-icon-search"></i>
              </el-input>
            </div>
            <el-tree
              ref="treeNo"
              clearable
              class="filter-tree"
              :data="dataNo"
              :props="defaultProps"
              default-expand-all
              :filter-node-method="filterNodeNo"
              @node-click="changeClick"
            >
              <span slot-scope="{ node,data }" class="custom-tree-node">
                <el-tooltip class="item" effect="dark" placement="top">
                  <div slot="content" v-html="data.funcDoc" v-if="data.funcDoc"></div>
                  <div slot="content" v-else>{{ node.label }}</div>
                  <span>{{ node.label }}</span>
                </el-tooltip>
              </span>
            </el-tree>
          </div>
          <!-- 表格结构 -->
          <div class="content-child">
            <div class="line-flex">
              <div style="width:90px">字段搜索：</div>
              <el-input v-model="keyword" clearable placeholder="请输入搜索的字段名称">
                <i slot="suffix" class="el-input__icon el-icon-search"></i>
              </el-input>
            </div>
            <el-table :data="currentData" border height="260" style="width: 100%" stripe>
              <el-table-column prop="logicColumnName" label="字段名称" align="center">
                <template scope="scope">
                  <div @click="tdWord(scope.row.logicColumnName)">{{ scope.row.logicColumnName }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="logicColumnType" label="字段类型" align="center">
                <template scope="scope">
                  <div @click="tdWord(scope.row.logicColumnName)">{{ scope.row.logicColumnType }}</div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <!-- 文本框 -->
        <div class="textarea-warp">
          <div class="new-title">编辑：</div>
          <el-input
            v-model="textarea"
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
            @blur="getWord($event)"
            @input="Sync"
          ></el-input>
        </div>
      </span>
      <span slot="footer" class="dialog-footer">
        <span>
          <el-button @click="validateExpression">校 验</el-button>
        </span>
        <span>
          <el-button @click="handleCloseAll">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </span>
    </el-dialog>
    <el-dialog title="校验返回信息" :visible.sync="dialogVisible2" width="50%" append-to-body>
      <span>{{ vaildResult }}</span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapMutations } from "vuex";
import metaData from "./components/metaData";
import typeMap from "./components/type_map";
import { GONGAN_STANDARD_NAMES } from "@/utils/modules/validate.js";
export default {
  components: {
    metaData
  },
  data() {
    return {
      isUpdateForm: false,
      objectTypeList: [
        {
          id: "string",
          name: "string"
        },
        {
          id: "timestamp",
          name: "timestamp"
        },
        {
          id: "int",
          name: "int"
        },
        {
          id: "long",
          name: "long"
        },
        {
          id: "double",
          name: "double"
        },
        {
          id: "boolean",
          name: "boolean"
        }
      ],
      selectedList: [],
      persentViewFoot: {},
      dis: false,
      ruleForm: {
        dataMapList: [],
        name: ""
      },
      tableRules: {
        logicColumnName: [
          {
            required: true,
            message: "请输入目标标识符",
            trigger: "blur"
          },
          {
            max: 30,
            message: "不超过30个字符",
            trigger: "blur"
          },
          {
            pattern: /^[a-zA-Z]+[_a-zA-Z0-9]*$/g,
            message: "英文、数字、下划线组合，英文开头",
            trigger: "blur"
          }
        ],
        logicColumnChineseName: [
          { required: true, message: "请输入目标名称", trigger: "blur" }
        ],
        logicColumnType: [
          { required: true, message: "请选择目标类型", trigger: "change" }
        ],
        rule: [{ required: false, message: "请选择规则", trigger: "change" }]
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入转换名称",
            trigger: ["blur", "change"]
          }
        ]
      },
      currentIndex: 0,
      dialogVisible: false,
      index: "",
      textarea: "",
      dialogVisible2: false,
      vaildResult: "",
      validFlag: false,
      start: "",
      end: "",
      dataNo: [],
      filterTextNo: "",
      checkData: [],
      keyword: "",
      dialogData: [],
      currentData: [],
      textareaarr: [],
      defaultProps: {
        children: "children",
        label: "functionNameEn"
      },
      loading: false,
      isLink: false
    };
  },
  computed: {
    ...mapGetters([
      "getViewFoot",
      "getOperatorInfo",
      "getSubmitInfo",
      "setSubmitInfo",
      "getDictionaryList",
      "getReadOnlyFlag",
      "getDelFlag"
    ]),
    flowList() {
      return this.$store.state.flow.flowList;
    }
  },
  mounted() {
    this.$store.commit("setDelFlag", false);
    this.persentViewFoot = JSON.parse(JSON.stringify(this.getViewFoot));
    this.initOpera();
    this.dialogData = JSON.parse(
      JSON.stringify(this.getSubmitInfo[this.getViewFoot.preNode].outPut)
    );
    this.currentData = JSON.parse(JSON.stringify(this.dialogData));
  },
  watch: {
    getViewFoot: {
      handler(val, old) {
        this.refresh();
      },
      deep: true
    },
    filterTextNo(val) {
      this.$refs.treeNo.filter(val);
    },
    keyword(val) {
      this.currentData = this.dialogData.filter(
        item => item.logicColumnName.indexOf(val) !== -1
      );
    },
    textarea(val) {
      this.validFlag = false;
    }
  },
  destroyed() {
    if (this.checkData.length != this.selectedList.length) {
      this.isUpdateForm = true;
      this.checkData = this.selectedList;
    }
    // 如果是删除节点禁止触发销毁钩子
    if (this.isUpdateForm && this.isLink) {
      this.$alert("当前内容有变更，需重连下一节点才生效", "提示", {
        confirmButtonText: "确定"
      });
    }
    if (this.getDelFlag) {
      this.$store.commit("setDelFlag", false);
    } else {
      const ids = this.persentViewFoot.id; // id
      const list = [];
      this.selectedList.forEach(item => {
        list.push(item.logicColumnName);
      });
      this.ruleForm.dataMapList.forEach(item => {
        if (list.indexOf(item.logicColumnName) !== -1) {
          item.isShow = true;
        } else {
          item.isShow = false;
        }
      });

      const value = {
        ruleForm: this.ruleForm,
        flag: true
      };

      const obj = {};
      obj[ids] = value;
      this.$store.commit("setOperatorInfo", obj); // 将对象存入store，kye-value形式
      // 存放本算子信息，最终提交用
      const submitIds = this.persentViewFoot.id; // id
      // 根据节点id匹配节点坐标
      const arr = this.flowList.nodeList.filter(
        item => this.persentViewFoot.id === item.id
      );
      const submitValue = {
        operateName: this.ruleForm.name,
        operateType: "6",
        location: `${arr[0].top},${arr[0].left}`,
        orderNumber: this.persentViewFoot.id,
        outPut: this.selectedList
      };
      const submitObj = {};
      submitObj[submitIds] = submitValue;
      this.$store.commit("setSubmitInfo", submitObj);
    }
  },
  methods: {
    ...mapMutations("flow", ["setNodeName"]),
    handleClose(done) {
      this.filterTextNo = "";
      done();
    },
    handleCloseAll() {
      this.filterTextNo = "";
      this.dialogVisible = false;
    },
    edit(index, row) {
      this.dialogVisible = true;
      this.index = index;
      this.textarea = row.rule;
      this.getAllExpression();
    },
    checkSelectable(row) {
      return !this.getReadOnlyFlag;
    },
    submit() {
      if (this.validFlag) {
        this.isUpdateForm = true;
        this.ruleForm.dataMapList[this.index].rule = this.textarea;
        this.dialogVisible = false;
        this.filterTextNo = "";
        this.textarea = "";
        this.textareaarr = [];
      } else {
        this.$message({ message: "请先进行校验", type: "warning" });
      }
    },
    filterNodeNo(value, data) {
      if (!value) return true;
      return data.functionNameEn.indexOf(value) !== -1;
    },
    getWord(e) {
      this.start = e.target.selectionStart;
      this.end = e.target.selectionEnd;
    },
    tdWord(val) {
      if (this.end > 0) {
        this.textarea = this.changeStr(
          this.textarea,
          this.start,
          this.end,
          val
        );
      } else {
        this.textareaarr.push(val);
        const arr = this.textareaarr.filter(s => s && s.trim());
        this.textarea = arr.toString().replace(/,/g, "");
      }
    },
    changeStr(str, index, end, changeStr) {
      this.end = 0;
      return str.substr(0, index) + changeStr + str.substr(end);
    },
    Sync(val) {
      this.textareaarr = [val];
    },
    changeClick(val) {
      this.tdWord(val.defaultExpression);
    },
    // 获取规则列表
    async getAllExpression() {
      const res = await this.$api.home.getAllExpression();
      if (res.data.resultCode === 0) {
        const arr = res.data.data;
        this.dataNo = [];
        for (const i in arr) {
          const obj = {
            functionNameEn: i,
            children: arr[i]
          };
          this.dataNo.push(obj);
        }
      }
    },
    // 校验规则
    async validateExpression() {
      if (!this.textarea) {
        this.$message({ message: "请输入校验规则", type: "warning" });
      } else {
        const arr = [];
        this.dialogData.forEach(item => {
          const obj = {};
          (obj.fieldFormat = item.sourceTimeFormat),
            (obj.fieldLength = Number(item.logicColumnLength)),
            (obj.fieldName = item.logicColumnName),
            (obj.fieldType = item.logicColumnType);
          arr.push(obj);
        });

        const params = {
          expression: this.textarea,
          inputFormat: arr
        };
        const res = await this.$api.home.validateExpression(params);
        this.vaildResult = res.data.resultMessage;
        if (res.data.resultCode === 0) {
          this.validFlag = true;
          this.$message({ message: "校验成功", type: "success" });
        } else {
          this.$message({ message: "校验失败", type: "error" });
          this.dialogVisible2 = true;
        }
      }
    },
    refresh() {
      this.ruleForm.name = this.getViewFoot.name;
    },
    initOpera() {
      const vm = this;
      if (vm.getViewFoot.nextNode) {
        vm.isLink = true;
      } else {
        vm.isLink = false;
      }
      if (
        vm.getOperatorInfo[vm.getViewFoot.id] &&
        vm.getOperatorInfo[vm.getViewFoot.id].flag
      ) {
        let res = JSON.parse(
          JSON.stringify(vm.getOperatorInfo[vm.getViewFoot.id])
        );
        vm.ruleForm = res.ruleForm;
        vm.selectOne();
      } else {
        // const obj = Object.assign(this.getViewFoot, { flag: true })
        vm.ruleForm.flag = true;
        vm.ruleForm.name = vm.getViewFoot.name;
        let data = [];
        if (
          vm.$store.state.tree.readOnlyFlag &&
          vm.getSubmitInfo[vm.getViewFoot.id].outPut
        ) {
          data = JSON.parse(
            JSON.stringify(vm.getSubmitInfo[vm.getViewFoot.id].outPut)
          );
          vm.ruleForm.dataMapList = data;
          vm.selectOne();
        } else {
          data = JSON.parse(
            JSON.stringify(vm.getSubmitInfo[vm.getViewFoot.preNode].outPut)
          );
          vm.getData(data);
        }
      }
    },
    vaildEnName(val) {
      this.isUpdateForm = true;
      if (this.ruleForm.dataMapList.length > 0) {
        for (let i = this.ruleForm.dataMapList.length - 1; i >= 0; i--) {
          const tempStr = this.ruleForm.dataMapList[i].logicColumnName;
          for (let j = 0; j < i; j++) {
            if (
              tempStr.toUpperCase() ===
              this.ruleForm.dataMapList[j].logicColumnName.toUpperCase()
            ) {
              this.$alert(
                `<p>第${i +
                  1}行，目标标识符${tempStr.toUpperCase()}重复，请修改</p>\n`,
                "信息",
                {
                  dangerouslyUseHTMLString: true,
                  confirmButtonText: "确定",
                  customClass: "tip-map-info",
                  type: "warning",
                  callback: action => {
                    return false;
                  }
                }
              );
              this.ruleForm.dataMapList[i].logicColumnName = "";
              return false;
            }
          }
          if (
            GONGAN_STANDARD_NAMES.includes(
              this.ruleForm.dataMapList[i].logicColumnName.toLowerCase()
            )
          ) {
            this.$alert(
              `<p>第${i +
                1}行，目标标识符${tempStr.toUpperCase()}属于标准名称，请修改</p>\n`,
              "信息",
              {
                dangerouslyUseHTMLString: true,
                confirmButtonText: "确定",
                customClass: "tip-map-info",
                type: "warning",
                callback: action => {
                  return false;
                }
              }
            );
            this.ruleForm.dataMapList[i].logicColumnName = "";
            return false;
          }
        }
      }
    },
    async getData(data) {
      const vm = this;
      vm.loading = true;
      let para = [];
      if (data.length > 0) {
        data.forEach(item => {
          const obj = {
            isStandard: item.isStandard ? item.isStandard : 0,
            logicColumnChineseName: item.logicColumnChineseName || "",
            logicColumnName: item.logicColumnName || "",
            logicColumnType: item.logicColumnType || "",
            rule: item.logicColumnName,
            isShow: true,
            logicColumnLength: item.logicColumnLength || "",
            sourceNodeHierarchy: item.sourceNodeHierarchy || "",
            sourceTimeFormat: item.sourceTimeFormat || ""
          };
          para.push(obj);
        });
        let res = await this.$api.home.buildStandardColumn(para);
        if (res.data.resultCode === 0) {
          vm.ruleForm.dataMapList = res.data.data;
          vm.selectAll();
        }
        vm.loading = false;
      }
    },
    selectOne() {
      const vm = this;
      vm.$refs.dataMap.clearSelection();
      vm.checkData = [];
      vm.$nextTick(() => {
        vm.ruleForm.dataMapList.forEach(item => {
          if (item.isShow === true || item.isShow === "true") {
            vm.checkData.push(item);
          }
          vm.$refs.dataMap.toggleRowSelection(item, item.isShow);
        });
      });
    },
    selectAll() {
      const vm = this;
      vm.$refs.dataMap.clearSelection();
      vm.checkData = [];
      vm.$nextTick(() => {
        vm.ruleForm.dataMapList.forEach(item => {
          vm.checkData.push(item);
          vm.$refs.dataMap.toggleRowSelection(item);
        });
      });
    },
    handleSelectionChange(val) {
      if (val.length > 0) {
        this.selectedList = val;
      } else {
        this.$message({ message: "请至少选则一项", type: "warning" });
      }
    },
    // 点击“目标字段名称”的加号， 打开数据元dialog,选择数据填入表格
    setMetaData(index, row) {
      this.currentIndex = index;
      this.$refs.metaData.openDialog(row);
    },
    // 从数据元信息dialog中获取目标字段名称，类型，描述信息
    getMetaData(data) {
      this.ruleForm.dataMapList[this.currentIndex].logicColumnName = data.bsf
        ? data.bsf
        : this.ruleForm.dataMapList[this.currentIndex].logicColumnName; // 目标字段标识-bsf标识符
      let res = this.vaildEnName(data.bsf);
      if (res != false) {
        // 增加提示重复目标数据标识功能
        this.ruleForm.dataMapList[this.currentIndex].isStandard = data.bsf
          ? 1
          : 0; // 作为标准

        this.ruleForm.dataMapList[
          this.currentIndex
        ].logicColumnChineseName = data.zwmc
          ? data.zwmc
          : this.ruleForm.dataMapList[this.currentIndex].logicColumnChineseName; // 目标数据中文名称zwmc

        this.ruleForm.dataMapList[this.currentIndex].logicColumnName = data.bsf
          ? data.bsf
          : this.ruleForm.dataMapList[this.currentIndex].logicColumnName; // 目标字段标识-bsf标识符

        this.ruleForm.dataMapList[this.currentIndex].logicColumnType = data.sjlx
          ? data.sjlx
          : this.ruleForm.dataMapList[this.currentIndex].logicColumnType; // 目标数据数据类型sjlx

        if (data.sjlx) {
          this.dis = false;
        }
      }
    },
    clearNewColumnInfo(idx, row) {
      row.isStandard = 0;
      row.logicColumnName = "";
      row.logicColumnChineseName = "";
      row.logicColumnType = "";
    },
    setName() {
      const data = {
        name: this.ruleForm.name,
        id: this.getViewFoot.id,
        that: this
      };
      this.setNodeName(data);
    }
  }
};
</script>
<style lang='scss' scoped>
.new-input {
  width: 50%;
}
.dialog-footer {
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
}
.new-flex {
  display: flex;
  justify-content: space-between;
}
.content-child {
  width: 49%;
  height: 300px;

  .filter-tree {
    overflow: auto;
    height: 260px;
  }
}
.textarea-warp {
  margin-top: 40px;
}

/deep/ {
  .el-dialog__header {
    display: flex;
    .el-dialog__title {
      color: #0090ff;
    }
  }
  .el-tree {
    .el-tooltip.item {
      display: inline-block;
      width: 350px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .el-tree-node__expand-icon {
      color: #0090ff;
      font-size: 14px;
    }
    .el-tree-node__expand-icon.is-leaf {
      color: transparent;
    }
  }
  .el-table .el-form-item__error {
    transform: scale(0.9);
    padding-top: 0;
    right: -40px;
  }
}
.no-check /deep/ .el-table th .el-checkbox {
  display: none;
}
.btn-block {
  position: absolute;
  right: 20px;
  top: 50px;
}
.new-title {
  // color: #0090ff;
  font-size: 16px;
  margin-bottom: 10px;
}
.new-flew {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 18px 0;
  .input-block {
    width: 240px;
    margin-left: 10px;
  }
}
.item {
  margin-right: 20px;
  &:last-child {
    margin-right: 0;
  }
}
.el-form-item {
  margin-right: 5px;
  margin-top: 0.16rem;
}
.text-required {
  color: red;
}
</style>
